package downloader

import (
	"code.google.com/p/log4go"
	"errors"
	"io/ioutil"
	"net/http"
	"strconv"
)

var err error

var logger log4go.Logger

type Downloader interface {
	Init(url, saverule, savepath, des string) (*Down, error)
	Down() error
	Cancel() bool
	State() *Down
}
type Down struct {
	Url      string
	Process  int
	Mime     string
	Size     int
	Des      string
	SaveRule string
	SavePath string
	SaveName string
	DId      string
}

func LogInit(l log4go.Logger) {
	logger = l
}
func DInit(url, saverule, savepath, des string) (downs *Down, err error) {
	downs = new(Down)
	downs.DId = getRandString(10)
	if !isDirExists(savepath) {
		return downs, errors.New("filepath is not exist")
	}
	downs.Url = url
	downs.SaveRule = saverule
	downs.SavePath = savepath
	downs.Des = des
	return downs, nil
}

func (d *Down) Down() {
	go logger.Info("Id\t" + d.DId + "\tis downloading...." + "\r\n")
	req, _ := http.NewRequest("GET", d.Url, nil)
	req.Header.Set("Cache-Control", "max-age=0")
	req.Header.Set("Connection", "close")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logger.Error(err.Error() + "\r\n")
		return
	}
	d.Size, _ = strconv.Atoi(resp.Header.Get("Content-Length"))
	d.Mime = resp.Header.Get("Content-Type")
	filebyte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logger.Error(err.Error() + "\r\n")
		return
	}
	switch d.SaveRule {
	case "md5":
		d.SaveName, err = getFileMd5(filebyte)
		if err != nil {
			logger.Error(err.Error() + "\r\n")
			return
		}
	case "rand":
		d.SaveName = getRandString(32)
	}

	//TODO 文件后缀名
	savesuffix, ok := MimeToSuffix(d.Mime)
	if !ok {
		savesuffix = ".uknow"
	}
	savepath := d.SavePath + d.SaveName + savesuffix
	err = save(filebyte, savepath)
	if err != nil {
		logger.Error(err.Error() + "\r\n")
		return
	}
	resp.Body.Close()
	go logger.Info("Id\t" + d.DId + "\tis ok...." + "\r\n")
}
